package com.wertop.viid.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.wertop.viid.common.annotation.LogOperation;
import com.wertop.viid.common.annotation.RequireAuth;
import com.wertop.viid.common.enums.InfoKind;
import com.wertop.viid.common.result.ConfirmStatusType;
import com.wertop.viid.common.result.ResponseStatusListObject;
import com.wertop.viid.common.result.ResponseStatusObject;
import com.wertop.viid.common.utils.Base64Utils;
import com.wertop.viid.common.utils.DateUtils;
import com.wertop.viid.common.validator.ValidatorUtils;
import com.wertop.viid.dao.RmsScreenshotDao;
import com.wertop.viid.dto.FaceListObject;
import com.wertop.viid.dto.FaceObject;
import com.wertop.viid.dto.SubImageInfoObject;
import com.wertop.viid.entity.CmsDevice;
import com.wertop.viid.entity.CmsPersonPath;
import com.wertop.viid.entity.RmsScreenshot;
import com.wertop.viid.service.CmsPersonPathService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description FaceController
 * @Author yempty
 * @Date 2020/6/18 11:27
 */
@Slf4j
@RestController
@RequestMapping("Faces")
@Api(tags = "人脸相关接口")
public class FaceController {
    @Resource
    private CmsPersonPathService cmsPersonPathService;
    @Resource
    private RmsScreenshotDao rmsScreenshotDao;

//    private final String imgUrl = "C:/Users/wertop/Desktop/";
    private final String imgUrl = "/upload/xmyc/picture/";

    @RequireAuth
    @PostMapping
    @ApiOperation("人脸批量新增")
    @LogOperation("人脸批量新增")
    public ResponseStatusListObject register(@RequestBody FaceListObject faceListObject) {
        List<CmsPersonPath> cmsPersonPathList = new ArrayList<>();
        List<RmsScreenshot> rmsScreenshotList = new ArrayList<>();
        boolean insertFlag = true;
        List<ResponseStatusObject> list = new ArrayList<>(faceListObject.getFaceObjects().size());
        ResponseStatusObject responseStatusObject;
        String errMsg;
        InfoKind infoKind;
        for (FaceObject faceObject : faceListObject.getFaceObjects()) {
            // 检验参数
            errMsg = ValidatorUtils.validateEntity(faceObject);
            if (StringUtils.isBlank(errMsg)) {
                infoKind = InfoKind.getByValue(faceObject.getInfoKind());
                if (infoKind == null) {
                    errMsg += "信息分类的值不符合要求.";
                } else {
                    switch (infoKind) {
                        case AUTO:
                            if (StringUtils.isBlank(faceObject.getDeviceId())) {
                                errMsg += "自动采集，设备编码必须填写.";
                            }
                            if (faceObject.getLeftTopX() == null || faceObject.getLeftTopY() == null
                                    || faceObject.getRightBtmX() == null || faceObject.getRightBtmY() == null) {
                                errMsg += "自动采集，记录人脸矩形框的左上角坐标和右下角坐标必须填写.";
                            }
                            break;
                        case MANUAL:
                            if (faceObject.getLocationMarkTime() == null) {
                                errMsg += "人工采集，位置标记时间必须填写.";
                            }
                            if (faceObject.getFaceAppearTime() == null) {
                                errMsg += "人工采集，出现时间必须填写.";
                            }
                            if (faceObject.getFaceDisAppearTime() == null) {
                                errMsg += "人工采集，消失时间必须填写.";
                            }
                            if (faceObject.getIsDetainees() == null) {
                                errMsg += "人工采集，是否在押人员必须填写.";
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
            if (StringUtils.isBlank(errMsg)) {
                responseStatusObject = ResponseStatusObject.create(faceObject.getFaceId(), ConfirmStatusType.OK);
            } else {
                responseStatusObject = ResponseStatusObject.create(faceObject.getFaceId(), ConfirmStatusType.Validate_Error.getCode(), errMsg);
            }
            list.add(responseStatusObject);
            //todo 信息入库
//            CmsPersonPath cmsPersonPath = new CmsPersonPath();
//            BeanUtils.copyProperties(faceObject,cmsPersonPath);
//            cmsPersonPath.setCreateTime(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()));
//            cmsPersonPathList.add(cmsPersonPath);
            //判断信息是否入库
            insertFlag = ObjectUtil.isNotEmpty(faceObject.getDeviceId());
            if (insertFlag) {
                List<CmsDevice> device = rmsScreenshotDao.getDevice(faceObject.getDeviceId());
                insertFlag = ObjectUtil.isNotEmpty(device) && 1 == device.get(0).getIsViid();
                log.info("----------设备信息result：{}",device);
            }
            log.info("----------设备编号为：{}，图片处理入库开关状态：{}", faceObject.getDeviceId(), insertFlag);
            RmsScreenshot rmsScreenshot = new RmsScreenshot();
            rmsScreenshot.setType(1);
            rmsScreenshot.setLeftTopX(faceObject.getLeftTopX().toString());
            rmsScreenshot.setLeftTopY(faceObject.getLeftTopY().toString());
            rmsScreenshot.setRightBottomX(faceObject.getRightBtmX().toString());
            rmsScreenshot.setRightBottomY(faceObject.getRightBtmY().toString());
            //图片信息
            List<SubImageInfoObject> subImageInfoObjects = faceObject.getSubImageList().getSubImageInfoObjects();
            String url = imgUrl + DateUtils.formatMonth(new Date()) + "/";
            File file = new File(url);
            if (!file.exists()) {
                file.mkdirs();
            }
            subImageInfoObjects.forEach(x -> {
                String fileName = url + DateUtils.format(DateUtil.date(x.getShotTime()), "yyyy-MM-dd-HH-mm-ss") + "-" + x.getType() + ".png";
                Base64Utils.Base64ToImage(x.getData(), fileName);
                if (x.getType().equals("14")) {
                    rmsScreenshot.setSnapshot(fileName);
                    rmsScreenshot.setScreenshotTime(DateUtils.format(DateUtil.date(x.getShotTime()), "yyyy-MM-dd HH:mm:ss"));
                } else if (x.getType().equals("11")) {
                    rmsScreenshot.setScreenshot(fileName);
                }
            });
            rmsScreenshot.setWebcamId(faceObject.getDeviceId());
            rmsScreenshot.setIsDis(0);
            rmsScreenshot.setPictureId(0L);
            rmsScreenshot.setObjectId(0L);
            rmsScreenshot.setMatched("0%");
            rmsScreenshot.setTaskTypeCode(2);
            rmsScreenshotList.add(rmsScreenshot);
        }
        String tableName = "rms_screenshot_" + DateUtils.formatMonth(new Date());
        if (insertFlag) {
            rmsScreenshotDao.insertScreenshot(rmsScreenshotList, tableName);
        }

//        cmsPersonPathService.saveBatch(cmsPersonPathList);
        return ResponseStatusListObject.create(list);
    }
}
